<template>
	<view class="parent">
		<view class="top">
			<uni-easyinput placeholder="请输入地址" v-model="address">
		<!-- 		<template #right>
					<button class="address" @click="sure">确定</button>
				</template> -->
			</uni-easyinput>
			<view class="tips">
				<view class="tip" v-for="item in locations" :key="item.id" @click="selAddress(item.location, item.name)">{{ item.name }}</view>
			</view>
		</view>
		<map class="map" :longitude="longitude" :latitude="latitude" :markers="markers" />
	</view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import env from '../factory/env';
import {setAddress,setLongitude,setLatitude} from '../store/global';

const address = ref('');
const latitude = ref('');
const longitude = ref('');
let showLocations = true;
type Location = {
	location: string;
	name: string;
	id: string;
};

type Marker = {
	longitude: string;
	latitude: string;
	id: number;
};

const markers = ref<Array<Marker>>([]);
const locations = ref<Array<Location>>([]);

uni.getLocation({
	type: 'wgs84',
	success: (res: any) => {
		longitude.value = res.longitude;
		latitude.value = res.latitude;
		const marker = {
			longitude: longitude.value,
			latitude: latitude.value,
			id: 1
		};
		markers.value.push(marker);
	}
});
const selAddress = (location: string, name: string) => {
	const arr = location.split(',');
	longitude.value = arr[0];
	latitude.value = arr[1];

	markers.value[0].longitude = arr[0];
	markers.value[0].latitude = arr[1];

	address.value = name;
	// showLocations = false;

	// setTimeout(() => {
	// 	showLocations = true;
	// }, 100);
	
	setAddress(address.value);
	setLongitude(longitude.value);
	setLatitude(latitude.value);
	
	uni.navigateBack()
};

// const sure = () => {
	
// 	setAddress(address.value);
// 	setLongitude(longitude.value);
// 	setLatitude(latitude.value);
	
// 	uni.navigateBack()
	
// };

watch(address, () => {

	if (address.value.replace(/\s+/g, '') && showLocations) {
		uni.request({
			url: env.gaodeApiUrl + '/assistant/inputtips',
			data: {
				key: env.gaodeKey,
				output: 'json',
				keywords: address.value,
				location: longitude.value + ',' + latitude.value
			},
			success: (res: any) => {
				locations.value = res.data.tips;
			},fail(res) {
			
				console.log(res)
			}
		});
	} else {
		locations.value = [];
	}
});
</script>

<style lang="scss">
.parent {
	position: relative;
	.top {
		position: absolute;
		top: 15px;
		left: 15px;
		right: 15px;
		z-index: 1000;
		.tips {
			max-height: 250px;
			background: rgba(#c6c6c6, 0.7);
			overflow-y: scroll;
			.tip {
				line-height: 30px;
				color: #3c7365;
				padding:0 10px;
			}
		}
	}
}
.map {
	width: 100vw;
	height: 100vh;
}
.input {
	margin: 15px;
}
.address {
	background: #a5d63f;
	color: white;
	width: 80px;
}
</style>
